package com.wyh.recketmq.seckill.controller;

import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;


/**
 * @author wuyuhan
 * @date 2021/5/15 17:56
 */
@RestController
public class OrderController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate<String,Long> redisTemplate;
    private static final String redis_key="orderNum";

    @RequestMapping("/orderNum")
    public Integer orderNum(){
        String orderNum = redisTemplate.opsForValue().get(redis_key) + "";
        return Integer.parseInt(orderNum);
    }

    @RequestMapping("/create")
    public String create(){
        Long orderNum = redisTemplate.opsForValue().decrement(redis_key);
        if (orderNum<0){
            redisTemplate.opsForValue().increment(redis_key);
            return "fail";
        }else {
            String orderStr=System.currentTimeMillis()+" has e order";
            //将json字符串发给mq
            SendResult sendResult = rocketMQTemplate.syncSend("rocket-orderDelay", MessageBuilder.withPayload(orderStr).build(),2000,3);
            return "true";
        }
    }

    @RequestMapping("/cancel")
    public String cancel(){
        Long orderNum = redisTemplate.opsForValue().increment(redis_key);
        String orderStr=System.currentTimeMillis()+" cancel e order";
        //将json字符串发给mq
        SendResult sendResult = rocketMQTemplate.syncSend("rocket-orderDelay", MessageBuilder.withPayload(orderStr).build(),2000,3);
        return "success";

    }
}
